import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

class ImageUploadComponent extends StatefulWidget {
  final XFile? imageFile;
  final String imageName;
  final Function(String) onImageNameChanged;
  final Function() onImageRemoved;
  final Function(XFile?) onImagePicked;

  ImageUploadComponent({
    Key? key,
    this.imageFile,
    required this.imageName,
    required this.onImageNameChanged,
    required this.onImageRemoved,
    required this.onImagePicked,
  }) : super(key: key);

  @override
  _ImageUploadComponentState createState() => _ImageUploadComponentState();
}

class _ImageUploadComponentState extends State<ImageUploadComponent> {
  final ImagePicker _picker = ImagePicker();

  Future<void> _pickImage() async {
    final XFile? pickedFile = await _picker.pickImage(source: ImageSource.gallery);
    widget.onImagePicked(pickedFile);
  }

  void _removeImage() {
    widget.onImageRemoved();
  }

  void _saveImageName(String name) {
    widget.onImageNameChanged(name);
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        if (widget.imageFile == null)
          Container(
            margin: EdgeInsets.all(10),
            child: ElevatedButton(
              onPressed: _pickImage,
              child: Text('选择图片'),
            ),
          )
        else
          Stack(
            alignment: Alignment.bottomRight,
            children: [
              Container(
                margin: EdgeInsets.all(10),
                child: Image.file(
                  File(widget.imageFile!.path),
                  width: 200,
                  height: 200,
                  fit: BoxFit.cover,
                ),
              ),
              Positioned(
                right: 10,
                bottom: 10,
                child: IconButton(
                  icon: Icon(Icons.delete_forever),
                  onPressed: _removeImage,
                ),
              ),
            ],
          ),
        TextFormField(
          initialValue: widget.imageName,
          onChanged: _saveImageName,
          decoration: InputDecoration(
            labelText: '资质名称',
            border: OutlineInputBorder(),
          ),
        ),
      ],
    );
  }
}